package com.test.blogsystem.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.test.blogsystem.Comment.Exception.BlogException;
import com.test.blogsystem.Mapper.UserMapper;
import com.test.blogsystem.Pojo.DO.UserInfo;
import com.test.blogsystem.Pojo.Require.LoginInfo;
import com.test.blogsystem.Pojo.Response.UserLoginResponse;
import com.test.blogsystem.Service.UserService;
import com.test.blogsystem.Utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserLoginResponse checkPassword(LoginInfo loginInfo) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserInfo::getUserName, loginInfo.getUserName()).eq(UserInfo::getDeleteFlag, 0);
        UserInfo userInfo = userMapper.selectOne(queryWrapper);

        if (userInfo == null) {
            throw new BlogException("用户未存在...", 0);
        }
        if (!loginInfo.getPassword().equals(userInfo.getPassword())) {
            throw new BlogException("密码错误...", -1);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("id", userInfo.getId());
        map.put("name", userInfo.getUserName());
        String key = JWTUtil.getKey(map);
        return new UserLoginResponse(userInfo.getId(), key);
    }
}
